<template>
	<a-card>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="horizontal">
			<a-row :gutter="16">
				<a-col :span="4" align="start">
					<u style="font-size: 24px">采购入库 </u>
				</a-col>
				<a-col :span="4">
					<a-form-item label="业务单号：" name="businessCode">
						{{formData.businessCode}}
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="业务状态：" name="businessCode">
						<a-tag v-if="formData.businessStatus === '0'" color="cyan" style="font-size: 24px;padding: 5px">
							{{formData.businessStatusName}}
						</a-tag>
						<a-tag v-if="formData.businessStatus === '1'" color="blue" style="font-size: 24px;padding: 5px">
							{{formData.businessStatusName}}
						</a-tag>
						<a-tag v-if="formData.businessStatus === '2'" color="purple" style="font-size: 24px;padding: 5px">
							{{formData.businessStatusName}}
						</a-tag>
					</a-form-item>
				</a-col>
				<a-col :span="3" align="end">
					<xn-page-select
						ref="xnreportIdPageSelectRef"
						v-model:value="reportId"
						placeholder="请选择打印格式"
						allow-clear
						show-search
						style="width:20%"
						:page-function="reportIdSelector"
						:disabled="!formData.id"
					/>
				</a-col>
				<a-col :span="8" align="end">
					<a-button type="primary" @click="toPrint" :loading="submitLoading" style="margin-left: 10px" :disabled="!formData.id">打印</a-button>
					<a-button type="primary" @click="newBusiness" :loading="submitLoading" style="margin-left: 10px">新建</a-button>
					<a-button type="primary" @click="onSubmit('0')" :loading="submitLoading" style="margin-left: 10px" >{{formData.businessStatus === '2' ? '重新复用' : formData.businessStatus === '1' ? '反审核' : '保存草稿'}}</a-button>
					<a-button type="primary" @click="onSubmit('1')" :loading="submitLoading" style="margin-left: 10px" danger :disabled="formData.businessStatus ==='2' || formData.businessStatus ==='1'">审核过账</a-button>
					<a-button type="default" @click="onSubmit('2')" :loading="submitLoading" style="margin-left: 10px" danger :disabled="formData.businessStatus!=='0'">作废</a-button>
					<a-button type="primary" style="margin-left: 10px" @click="onClose">关闭</a-button>

				</a-col>
			</a-row>


			<!--			<a-form-item label="业务类型：" name="businessType">-->
			<!--				<a-select v-model:value="formData.businessType" placeholder="请选择业务类型"-->
			<!--						  :options="businessTypeOptions"/>-->
			<!--			</a-form-item>-->
			<a-row :gutter="16">
				<a-col :span="4">
					<a-form-item label="入库门店：" name="businessStorageStoreId">
						<xn-page-select
							ref="xnbusinessStorageStoreIdPageSelectRef"
							v-model:value="formData.businessStorageStoreId"
							placeholder="请选择入库门店"
							allow-clear
							show-search
							:page-function="businessStorageStoreIdSelector"
							:echo-function="businessStorageStoreIdEcho"
							@change="setStoreageData(formData.businessStorageStoreId, 0)"
							:disabled="tableData.records.length>0"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="入库仓库：" name="businessStorageStorageId">
						<xn-page-select
							ref="xnbusinessStorageStorageIdPageSelectRef"
							v-model:value="formData.businessStorageStorageId"
							placeholder="请选择入库仓库"
							allow-clear
							show-search
							@change="locationChange"
							:page-function="businessStorageStorageIdSelector"
							:echo-function="businessStorageStorageIdEcho"
							:disabled="tableData.records.length>0"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="采购员：" name="businessSalesmanId">
						<xn-page-select
							ref="xnbusinessSalesmanIdPageSelectRef"
							v-model:value="formData.businessSalesmanId"
							placeholder="请选择业务员ID"
							allow-clear
							show-search
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:page-function="businessSalesmanIdSelector"
							:echo-function="businessSalesmanIdEcho"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="供应商：" name="businessObjectId">
						<xn-page-select
							ref="xnbusinessObjectIdPageSelectRef"
							v-model:value="formData.businessObjectId"
							placeholder="请选择供应商"
							allow-clear
							show-search
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:page-function="businessObjectIdSelector"
							:echo-function="businessObjectIdEcho"
							@change="businessObjectIdChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" hidden="">
					<a-form-item label="供应商名称：" name="businessObjectName">
						<a-input v-model:value="formData.businessObjectName" placeholder="请输入供应商名称"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="供应商地址：" name="businessObjectAddress">
						<a-input v-model:value="formData.businessObjectAddress" placeholder="请输入供应商地址" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="供应商电话：" name="businessObjectTel">
						<a-input v-model:value="formData.businessObjectTel" placeholder="请输入供应商电话" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="经手人ID：" name="businessHandlerId">
						<xn-page-select
							ref="xnbusinessHandlerIdPageSelectRef"
							v-model:value="formData.businessHandlerId"
							placeholder="请选择经手人ID"
							allow-clear
							show-search
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:page-function="businessHandlerIdSelector"
							:echo-function="businessHandlerIdEcho"
						/>
					</a-form-item>
				</a-col>

				<a-col :span="4" v-show="advanced">
					<a-form-item label="运单号：" name="businessWaybillNumber">
						<a-input v-model:value="formData.businessWaybillNumber" placeholder="请输入运单号" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="包装方式：" name="businessPackagingMethod">
						<a-input v-model:value="formData.businessPackagingMethod" placeholder="请输入包装方式" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="承运人：" name="businessCarrierId">
						<xn-page-select
							ref="xnbusinessCarrierIdPageSelectRef"
							v-model:value="formData.businessCarrierId"
							placeholder="请选择承运人"
							allow-clear
							show-search
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:page-function="businessCarrierIdSelector"
							:echo-function="businessCarrierIdEcho"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="合计件数：" name="businessNumberProduction">
						<a-input v-model:value="formData.businessNumberProduction" placeholder="请输入合计数量" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="商品种类：" name="businessNumberCategory">
						<a-input v-model:value="formData.businessNumberCategory" disabled placeholder="请输入商品种类"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="合计数量：" name="businessTotalNumber">
						<a-input v-model:value="formData.businessTotalNumber" disabled placeholder="请输入合计数量"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="合计金额：" name="businessTotalAmount">
						<a-input v-model:value="formData.businessTotalAmount" disabled placeholder="请输入合计金额" prefix="￥" suffix="RMB"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="折让金额：" name="businessDiscountAmount">
						<a-input v-model:value="formData.businessDiscountAmount" default-value="0" @change="toTotal()" prefix="￥" suffix="RMB" type="number" step="0.01" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
								 placeholder="请输入折让金额" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="应付金额：" name="businessPayableAmount">
						<a-input v-model:value="formData.businessPayableAmount" disabled placeholder="请输入应付金额" prefix="￥" suffix="RMB"
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="实付金额：" name="businessPayAmount">
						<a-input v-model:value="formData.businessPayAmount" default-value="0" placeholder="请输入实付金额"  allow-clear @change="toTotal()" prefix="￥" suffix="RMB" type="number" step="0.01" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="付款账户：" name="businessAccountId">
						<xn-page-select
							ref="xnbusinessAccountIdPageSelectRef"
							v-model:value="formData.businessAccountId"
							placeholder="请选择付款账户"
							allow-clear
							show-search
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:page-function="businessAccountIdSelector"
							:echo-function="businessAccountIdEcho"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="待付金额：" name="businessPendingPayAmount">
						<a-input v-model:value="formData.businessPendingPayAmount" default-value="0" prefix="￥" suffix="RMB" disabled
								 allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4" >
					<a-form-item label="付款期限：" name="businessPaymentDeadline">
						<a-date-picker v-model:value="formData.businessPaymentDeadline" value-format="YYYY-MM-DD" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
									   placeholder="请选择付款期限" style="width: 100%"/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="整单备注：" name="businessRemark">
						<a-input v-model:value="formData.businessRemark" placeholder="请输入整单备注" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="摘要：" name="businessAbstract">
						<a-input v-model:value="formData.businessAbstract" placeholder="请输入整单备注" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="2" style="align-items: center;padding-top: 5px">
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '更多' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
					</a>
				</a-col>
			</a-row>

			<s-table
				ref="tableRef"
				:columns="columns"
				:data="loadData"
				:alert="options.alert.show"
				bordered
				:row-key="(record) => record.id"
				:tool-config="toolConfig"
				:row-selection="options.rowSelection"
				compSize="small"
				@columnChange="columnChange"
			>
				<template #operator class="table-operator">
					<a-space>
						<a-button type="primary" @click="productionSelectorPlusRef.showProductionsPlusModal()" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'" v-show="formData.businessStorageStorageId"
								  v-if="hasPerm('supplierPurchaseInventoryAdd')">
							<template #icon>
								<plus-outlined/>
							</template>
							添加商品
						</a-button>
						<xn-batch-delete
							v-if="hasPerm('supplierPurchaseInventoryBatchDelete')" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							:selectedRowKeys="selectedRowKeys"
							@batchDelete=""
						/>
					</a-space>

				</template>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'detailProductionBatch'">
						<a-input
							v-model:value="detailData[record.detailSn -1 ].detailProductionBatch"
							style="display:flex; width: 100%; border: none; text-align: center" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
						/>
					</template>
					<template v-if="column.dataIndex === 'detailDateManufacture'">
						<a-date-picker v-model:value="detailData[record.detailSn -1 ].detailDateManufacture" placeholder="请选择生产日期" value-format="YYYY-MM-DD" style="display:flex; width: 100%; border: none; text-align: center" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"/>
					</template>
					<template v-if="column.dataIndex === 'detailNumber'">
						<a-input-number
							v-model:value="detailData[record.detailSn -1 ].detailNumber"
							placeholder="数量"
							style="display:flex; width: 100%; border: none; text-align: center"
							@change="totalNumber(record)" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
						/>
					</template>
					<template v-if="column.dataIndex === 'detailNumberGift'">
						<a-input-number
							v-model:value="detailData[record.detailSn -1 ].detailNumberGift"
							placeholder="赠送数量"
							default-value="0"
							style="display:flex; width: 100%; border: none; text-align: center"
							@change="totalNumber(record)" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
						/>
					</template>
					<template v-if="column.dataIndex === 'detailNumberTotal'">
						{{ record.detailNumberTotal }}
					</template>
					<template v-if="column.dataIndex === 'detailPrice'">
						<a-input-number
							v-model:value="detailData[record.detailSn -1 ].detailPrice"
							placeholder="单价"
							style="display:flex; width: 100%; border: none; text-align: center"
							@change="totalNumber(record)" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
						/>
					</template>
					<template v-if="column.dataIndex === 'detailAmount'">
						{{ detailData[record.detailSn - 1].detailAmount }}
					</template>
					<template v-if="column.dataIndex === 'detailRemark'">
						<a-input
							v-model:value="detailData[record.detailSn -1 ].detailRemark"
							style="display:flex; width: 100%; border: none; text-align: center" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
						/>
					</template>
					<template v-if="column.dataIndex === 'detailStorageLocation'">
						<a-select
							v-model:value="detailData[record.detailSn -1 ].detailStorageLocation"
							:options="locationOptions"
							style="display:flex;width:100%;"
							:bordered="false"
							:showArrow="false"
							show-search
							allow-clear
							:disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'"
							placeholder="请选择库位"
							:field-names="{
										label:'locationName',
										value:'id'
									}"
							:filter-option="locationFilterOption"
							@change="locationChange"
							@search = "handleSearch"
							@popupScroll="handlePopupScroll"
						>
						</a-select>
					</template>
					<template v-if="column.dataIndex === 'action'">
						<a-space>
							<a-popconfirm title="确定要删除吗？" @confirm="deleteDetail(record)">
								<a-button type="link" danger size="small" :disabled="formData.businessStatus ==='1' || formData.businessStatus ==='2'">删除</a-button>
							</a-popconfirm>
						</a-space>
					</template>
				</template>
			</s-table>


		</a-form>
	</a-card>
	<xn-production-selector
		ref="productionSelectorPlusRef"
		:categories-tree-api="selectorApiFunction.categoriesTreeApi"
		:productions-page-api="selectorApiFunction.productionsPageApi"
		data-type="object"
		:productions-show="false"
		:locationStorage="formData.businessStorageStorageId"
		:productionSupplier="formData.businessObjectId"
		@onBack="productionsCallBack"
	/>
</template>

<script setup name="supplierPurchaseInventoryForm">
import tool from '@/utils/tool'
import {ref,onMounted} from "vue";
import {cloneDeep, isEmpty} from 'lodash-es'
import {required} from '@/utils/formRules'
import { globalStore } from '@/store'
import supplierBusinessMainApi from '@/api/supplier/business/supplierBusinessMainApi'
import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";
import supplierUserApi from "@/api/supplier/structure/supplierUserApi";
import supplierStoragesApi from "@/api/supplier/warehouse/supplierStoragesApi";
import supplierCarrierApi from "@/api/supplier/base/supplierCarrierApi";
import supplierStoresApi from "@/api/supplier/base/supplierStoresApi";
import supplierBusinessDetailApi from "@/api/supplier/business/supplierBusinessDetailApi";
import supplierCategoriesApi from "@/api/supplier/base/supplierCategoriesApi";
import supplierProductionsApi from "@/api/supplier/base/supplierProductionsApi";
import supplierStoresLocationApi from "@/api/supplier/warehouse/supplierStoresLocationApi";
import { hiprint } from "vue-plugin-hiprint"
import publicReportsApi from "@/api/supplier/setting/publicReportsApi";
import homeCompanyApi from "@/api/home/setting/homeCompanyApi";
import sysColumnsSettingApi from "@/api/sys/setting/sysColumnsSettingApi";
import supplierAccountApi from "@/api/supplier/finance/supplierAccountApi";
import {message} from "ant-design-vue";
// 抽屉状态
const open = ref(false)
const emit = defineEmits({columnChange:null,successful: null, closed: null})
const formRef = ref()
//商品选择器
const productionSelectorPlusRef = ref()
//定义一个数组，用于存明细数据
const detailData = ref([])
const tableData = ref({records:[]})
// 查询区域显示更多控制
const advanced = ref(false)
const toggleAdvanced = () => {
	advanced.value = !advanced.value
}
//初始化设置表格列的显隐设置
onMounted(async() =>{
	//查找设置的显隐设置
	const res = await sysColumnsSettingApi.sysColumnsSettingDetail({columnsTableNo: "EN"})
	if(res){
		columnsData.value = res
		columns.value = JSON.parse(Object.assign({}, res).columnsSetting)
	}
} )
//当列设置被修改，接到子组件的修改通知后立刻保存设置到数据表中
const columnChange =(v)=> {
	columns.value = v
	columnsData.value.columnsSetting = JSON.stringify(v)
	columnsData.value.columnsTableNo = "EN"
	sysColumnsSettingApi.sysColumnsSettingSubmitForm(columnsData.value, columnsData.value.id).then((res) => {
		columnsData.value = res
	})
}

//打印报表
const reportId = ref()
const reportOptions = ref([])
const printData = ref({})
const reportSearchParams = ref({
	current: 1, //当前页
	size: 20,
	pages: 0, //共多少页
	total: 0,
	reportType: 'EN',
	searchKey: ''
})
const getReportOptions = (isScroll = false) => {
	publicReportsApi.publicReportsPage(reportSearchParams.value).then((res) => {
		reportSearchParams.value.pages = res.pages //共多少页
		reportSearchParams.value.current = res.current //当前页
		reportSearchParams.value.total = res.total
		if (isScroll == false) {
			reportOptions.value = []
		}
		reportOptions.value = [...reportOptions.value, ...res.records]
		for (let i = 0; i < reportOptions.value.length; i++) {
			if (reportOptions.value[i].reportDefault == '1') {
				reportId.value = reportOptions.value[i].id
				break
			}
		}
	})
}
//定义库位下拉框
const locationOptions = ref([])
const searchParams = ref({
	current: 1,
	size:10,
	pages:0,
	total:0,
	searchKey:""
})
const getLocationOptions = (isScroll=false) => {
	supplierStoresLocationApi.supplierStoresLocationPage(searchParams.value).then((res) => {
		searchParams.value.pages = res.pages //共多少页
		searchParams.value.current = res.current//当前页
		searchParams.value.total = res.total
		if (isScroll==false){ //如果不是下拉触发，则清空原有的数据源重新加载
			locationOptions.value = []
		}
		//将本次拉取的数据与原有的数据源合并
		locationOptions.value = [...locationOptions.value,...res.records]
	})
}
//下拉触发
const handlePopupScroll = (e)=>{
	const { target } = e;
	const { scrollTop, scrollHeight, clientHeight } = target;
	if (scrollTop + 2 + clientHeight >= scrollHeight) {
		// 已经到达底部，触发分页逻辑
		// todo 这里就可以触发加载下一页请求  具体函数根据当前业务需求来定
		if(searchParams.value.current<searchParams.value.pages){//后面还有
			searchParams.value.current = searchParams.value.current +1
			getLocationOptions(true);//这里是下拉加载，不清空原来的数据
		}
	}
}
//根据手输入进行过滤
const locationFilterOption = (input,locationOptions) =>{
	return `${locationOptions.locationName}`.includes(`${input || ''}`)
}
//根据输入的关键字到后端查找，并列新数据源
const handleSearch = (value)=>{
	searchParams.value.searchKey = value
	searchParams.value.current = 1
	searchParams.value.locationStore = formData.value.businessStorageStorageId
	getLocationOptions(false)
}
const locationChange=()=>{//当选定数据后，根据ID到后端查询该账户的详情，并有选择地赋给页控件
	searchParams.value = {
		current: 1,
		size:10,
		pages:0,
		total:0,
		searchKey:"",
		locationStore: formData.value.businessStorageStorageId
	}
	getLocationOptions(false)
}
// 传递商品选择器需要的API
const selectorApiFunction = {
	categoriesTreeApi: (param) => {
		return supplierCategoriesApi.categoriesTreeSelector(param).then((data) => {
			const tree = [
				{
					id: '',
					parentId: '0',
					name: '全部分类',
					children: data
				}
			]
			return Promise.resolve(tree)
		})
	},
	productionsPageApi: (param) => {
		return supplierProductionsApi.supplierProductionsPage(param).then((data) => {
			return Promise.resolve(data)
		})
	}
}
// 产品选择器回调
const productionsCallBack = (value) => {
	value.forEach((item, index) => {
		item.detailSn = detailData.value.length + 1
		item.detailProductionId = item.id
		item.detailUnit = item.productionUnit
		item.detailNumber = 1
		item.detailNumberGift = 0
		item.detailNumberTotal = item.detailNumber + item.detailNumberGift
		item.detailPrice = item.productionPriceProcureLast  //最近一次采购单价
		item.detailAmount = item.productionPriceProcureLast * item.detailNumber
		if (item.productionUnitAuxiliary !== '') {
			if (item.productionUnitAuxiliary !== null) {
				let unitAuxiliary = ""
				const auxiliaryList = JSON.parse(item.productionUnitAuxiliary)
				auxiliaryList.forEach((itemA) => {
					if(item.detailNumberTotal / itemA.conversion > 1) {
						unitAuxiliary = unitAuxiliary + Math.trunc(item.detailNumberTotal / itemA.conversion) + itemA.unit + Math.trunc(item.detailNumberTotal % itemA.conversion) + item.productionUnit + ";"
					}
				})
				item.detailNumberAuxiliary = unitAuxiliary
			}
		}
		item.detailStorageLocation = item.productionLocationIds ? item.productionLocationIds[0] : null
		item.visible = 1
		delete item.id
		detailData.value.push(item)
	})
	locationChange()
	toTotal()
	tableRef.value.refresh()
}

// 表单数据
const formData = ref({})
const submitLoading = ref(false)
const tableRef = ref()
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
const columns = ref([
		{
		title: '序号',
		dataIndex: 'detailSn'
	 	},
		{
			title: '商品编码',
			dataIndex: 'productionCode',
			align: 'center'
		},
		{
			title: '商品条码',
			dataIndex: 'productionBarcode',
			align: 'center'
		},
		{
			title: '商品名称',
			dataIndex: 'productionName',
			align: 'center'
		},
		{
			title: '批次',
			dataIndex: 'detailProductionBatch',
			align: 'center',
			width: 100
		},
		{
			title: '生产日期',
			dataIndex: 'detailDateManufacture',
			align: 'center',
			width: 150
		},
		{
			title: '单位',
			dataIndex: 'detailUnit',
			align: 'center'
		},
		{
			title: '数量',
			dataIndex: 'detailNumber',
			width: 80,
			align: 'center',
			needTotal: true
		},
		{
			title: '单价',
			dataIndex: 'detailPrice',
			width: 100,
			align: 'center'
		},
		{
			title: '金额',
			dataIndex: 'detailAmount',
			align: 'center',
			needTotal: true
		},
		{
			title: '赠送数量',
			dataIndex: 'detailNumberGift',
			width: 120,
			align: 'center',
			needTotal: true
		},
		{
			title: '合计数量',
			dataIndex: 'detailNumberTotal',
			width: 120,
			align: 'center',
			needTotal: true
		},
		{
			title: '辅助数量',
			dataIndex: 'detailNumberAuxiliary',
			align: 'center'
		},
		{
			title: '入库库位',
			dataIndex: 'detailStorageLocation',
			align: 'center',
			width: 150,
		},
		{
			title: '备注',
			dataIndex: 'detailRemark',
			width: 150,
			align: 'center'
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		}
])
const columnsData = ref({})
const selectedRowKeys = ref([])
// 列表选择配置
const options = {
	// columns数字类型字段加入 needTotal: true 可以勾选自动算账
	alert: {
		show: false,
		clear: () => {
			selectedRowKeys.value = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
const loadData = async (parameter) => {
	tableData.value.records = []
	for (let i = 0; i < parameter.size; i++) {
		if ((parameter.size * (parameter.current - 1) + i < detailData.value.length) && detailData.value[parameter.size * (parameter.current - 1) + i].visible === 1) {
			tableData.value.records.push(detailData.value[parameter.size * (parameter.current - 1) + i])
		}
	}
	tableData.value.total = detailData.value.length
	tableData.value.size = parameter.size
	tableData.value.current = parameter.current
	return Promise.resolve(tableData.value)
}
const deleteDetail = (record) => {
	// detailData.value.splice(record.detailSn -1 ,1)
	detailData.value[record.detailSn - 1].visible = 0//逻辑删除
	detailData.value.forEach((item, index) => {
		detailData.value[index].detailSn = index + 1
	})
	tableRef.value.refresh()
	toTotal()
}
const totalNumber = (record) => {
	//合计数字
	detailData.value[record.detailSn - 1].detailNumberTotal = detailData.value[record.detailSn - 1].detailNumber + detailData.value[record.detailSn - 1].detailNumberGift
	//计算金额
	detailData.value[record.detailSn - 1].detailAmount = (detailData.value[record.detailSn - 1].detailNumber * detailData.value[record.detailSn - 1].detailPrice).toFixed(2)
	//计算辅助数量
	if (record.productionUnitAuxiliary !== '') {
		if (record.productionUnitAuxiliary !== null) {
			let unitAuxiliary = ""
			const auxiliaryList = JSON.parse(record.productionUnitAuxiliary)
			auxiliaryList.forEach((item) => {
				if(record.detailNumberTotal / item.conversion > 1){
					unitAuxiliary = unitAuxiliary + Math.trunc(record.detailNumberTotal / item.conversion) + item.unit + Math.trunc(record.detailNumberTotal % item.conversion) + record.productionUnit + ";"
				}
			})
			detailData.value[[record.detailSn - 1]].detailNumberAuxiliary = unitAuxiliary
			record.detailNumberAuxiliary = unitAuxiliary
		}
	}
	//汇总计算
	toTotal()
}
const toTotal = () => {
	//汇总计算
	let numberCategory = 0
	let totalNumber = 0
	let totalAmount = 0
	detailData.value.forEach((detail) => {
		if(detail.visible === 1){  //已经删除的记录不参与计算
			numberCategory = numberCategory + 1
			totalNumber = totalNumber + detail.detailNumberTotal * 1  //含赠送
			totalAmount = totalAmount + detail.detailAmount * 1
		}
	})
	formData.value.businessNumberCategory = numberCategory  //品种数
	formData.value.businessTotalNumber = totalNumber   //总数量含赠送
	formData.value.businessTotalAmount = totalAmount   //总金额
	formData.value.businessPayableAmount = totalAmount - parseFloat(formData.value.businessDiscountAmount)  //应付金额 = 总金额 - 折让金额
	formData.value.businessPendingPayAmount = totalAmount - parseFloat(formData.value.businessDiscountAmount) - parseFloat(formData.value.businessPayAmount) //应付金额-已付金额 = 待付金额


}
const xnbusinessObjectIdPageSelectRef = ref();
let businessObjectData = []
const businessObjectIdSelector = (param) => {
	return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:"0"})).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.objectName,
					id: item.id,
					address: item.objectAddress,
					tel: item.objectTel
				};
			});
		}
		businessObjectData = [...businessObjectData,...data.records]
		return Promise.resolve(data)
	})
}
const businessObjectIdEcho = (param) =>{
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessObjectIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}
//补齐供应商的地址和电话
const businessObjectIdChange = (value) =>{
	let index = businessObjectData.findIndex(function (businessObject){
		return businessObject.id === value
	})
	formData.value.businessObjectName = businessObjectData[index].name
	formData.value.businessObjectAddress = businessObjectData[index].address
	formData.value.businessObjectTel = businessObjectData[index].tel
}

const xnreportIdPageSelectRef = ref();
const reportIdSelector = (param) => {
	return publicReportsApi.publicReportsPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				if (item.reportDefault === '1') {
					reportId.value = item.id
				}
				return {
					name: item.reportName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}

const xnbusinessHandlerIdPageSelectRef = ref();
const businessHandlerIdSelector = (param) => {
	return supplierUserApi.userPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.name,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const businessHandlerIdEcho = (param) =>{
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessHandlerIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}

const xnbusinessSalesmanIdPageSelectRef = ref();
const businessSalesmanIdSelector = (param) => {
	return supplierUserApi.userPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.name,
					id: item.id,

				};
			});
		}
		return Promise.resolve(data)
	})
}
const businessSalesmanIdEcho = (param) =>{
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessSalesmanIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}

const xnbusinessStorageStoreIdPageSelectRef = ref();
const businessStorageStoreIdSelector = (param) => {
	return supplierStoresApi.supplierStoresPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.storeName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const businessStorageStoreIdEcho = (param) =>{
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessStorageStoreIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}
// 门店选择后查询对应的仓库
const setStoreageData = (storeId, type) => {
	if (storeId) {
		const xnStoragePageSelectParam = {
			current: 1,
			parentId: storeId
		}
		formData.value.businessStorageStorageId = undefined
		xnbusinessStorageStorageIdPageSelectRef.value.onPage(xnStoragePageSelectParam);
	} else {
		formData.value.businessStorageStorageId = undefined
		xnbusinessStorageStorageIdPageSelectRef.value.onPage({current: 1});
	}
}
const xnbusinessStorageStorageIdPageSelectRef = ref();
const businessStorageStorageIdSelector = (param) => {
	return supplierStoragesApi.supplierStoragesPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.storeName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const businessStorageStorageIdEcho = (param) => {
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessStorageStorageIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}
const xnbusinessCarrierIdPageSelectRef = ref();
const businessCarrierIdSelector = (param) => {
	return supplierCarrierApi.supplierCarrierPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.carrierName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const businessCarrierIdEcho = (param) => {
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessCarrierIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}
const xnbusinessAccountIdPageSelectRef = ref()
const businessAccountIdSelector = (param) => {
	return supplierAccountApi.supplierAccountPage(param).then((data) => {
		if(data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.accountName,
					id:item.id
				}
			})
		}
		return Promise.resolve(data)
	})
}
const businessAccountIdEcho = (param) => {
	let echoList = []
	let echo =  {}
	for(var i=0;i<param.idList[0].length;i++){
		echo.name = formData.value.businessAccountIdName
		echo.id = param.idList[0][i]
		echoList.push(echo)
	}
	return Promise.resolve(echoList)
}

// 打开抽屉
const onOpen = async (record) => {
	formData.value.businessDiscountAmount = 0 //折让金额0
	formData.value.businessPayAmount = 0 // 实付金额
	formData.value.businessPendingPayAmount = 0// 待付金额
	open.value = true
	if (record) {
		console.log(record)
		//为表格库位下拉准备数据
		searchParams.value.locationStore = record.businessStorageStorageId
		getLocationOptions(false)//获取库位下拉信息
		// getReportOptions(false) //获取打印报表下拉信息
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
		nextTick(() =>{
			supplierBusinessDetailApi.supplierBusinessDetailList({detailBusinessId: record.id}).then((res) => {
				res.forEach(detail => {
					detail.visible = 1
				})
				detailData.value=res
				console.log(detailData.value)
				tableRef.value.refresh()
			})
		})
	}
	nextTick(() => {
		xnbusinessObjectIdPageSelectRef.value.onPage({current: 1});
		xnbusinessHandlerIdPageSelectRef.value.onPage({current: 1});
		xnbusinessSalesmanIdPageSelectRef.value.onPage({current: 1});
		xnbusinessStorageStoreIdPageSelectRef.value.onPage({current: 1});
		xnbusinessStorageStorageIdPageSelectRef.value.onPage({current: 1});
		xnbusinessCarrierIdPageSelectRef.value.onPage({current: 1});
		xnbusinessAccountIdPageSelectRef.value.onPage({current: 1});
		xnreportIdPageSelectRef.value.onPage({current: 1 , reportType: 'EN'});
		tableRef.value.refresh()
	});

}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	formData.value = {}
	detailData.value = []
	businessObjectData = []
	open.value = false
	emit('closed')
}
// 默认要校验的
const formRules = {
	businessStorageStoreId: [required('请选择入库门店')],
	businessStorageStorageId: [required('请选择入库仓库')],
	businessObjectId: [required('请输入业务对象')]
}
//新建
const newBusiness = () => {
	formRef.value.resetFields()
	formData.value.id = null
	formData.value.businessObjectCode = null
	formData.value.businessObjectIdName = null
	formData.value.businessPaymentStatusName = null
	formData.value.businessSalesManIdName = null
	formData.value.createTime = null
	formData.value.createUserName = null
	formData.value.updateTime = null
	formData.value.updateUser = null
	formData.value.businessDiscountAmount = 0 //折让金额0
	formData.value.businessPayAmount = 0 // 实付金额
	formData.value.businessPendingPayAmount = 0// 待付金额
	formData.value.businessStatus = '0' //业务状态先暂定0
	formData.value.businessStatusName = '草稿'
	formData.value.businessObjectPayableBefore = null
	formData.value.businessObjectPayableAfter = null
	formData.value.businessAccountBalanceBefore = null
	formData.value.businessAccountBalanceAfter = null
	formData.value.businessAbstract = null
	formData.value.businessRemark = null
	detailData.value = []
	tableRef.value.refresh()
}
//获取基础信息
const getOwnerCompany = async () => {
	printData.value = formData.value
	console.log(printData.value)
	printData.value.businessDetail = detailData.value
	await homeCompanyApi.homeCompanyDetail({id: globalStore().userInfo.companyId }).then((res) => {
		printData.value.companyName = res.companyName
		printData.value.companyTel = res.companyTel
		printData.value.companyAddress = res.companyAddress
		printData.value.printDate = tool.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
	})
}
//打印
const toPrint = async () => {
	await getOwnerCompany()
	publicReportsApi.publicReportsDetail({ id: reportId.value }).then((data) => {
		var hiprintTemplate = new hiprint.PrintTemplate({
			template: JSON.parse(Object.assign({}, data).reportContent)
		})
		hiprintTemplate.print(printData.value)
	})
}
// 验证并提交数据
const onSubmit = (businessStatus) => {
	formRef.value
		.validate()
		.then(() => {
			const newDetailData = []
			detailData.value.forEach((item) => {
				if (item.visible === 1) { //筛一下，把删除掉的记录不要了
					newDetailData.push(item)
				}
			})
			formData.value.details = newDetailData
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			formDataParam.businessStatus = businessStatus
			formDataParam.businessType = 'EN'
			formDataParam.businessSettlementType= '1' //付款
			if(formDataParam.businessPayAmount*1 > 0 && formDataParam.businessAccountId === undefined){
				message.warn('请选择结算账户')
				submitLoading.value = false
				return
			}
			//构建摘要
			formDataParam.businessAbstract = "采购入库" + newDetailData[0].productionName + "等" + newDetailData.length + "种商品，共计" + formDataParam.businessTotalAmount + "元"
			supplierBusinessMainApi
				.supplierBusinessMainSubmitForm(formDataParam, formDataParam.id)
				.then((res) => {
					formData.value = res
					// onClose()
					// emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
		.catch(() => {
		})
}
// 抛出函数
defineExpose({
	onOpen
})
</script>
